import React, {Component, Fragment} from 'react';
import {Card, Button, Table, Image, message, Input, Modal} from 'antd';
import {ExclamationCircleOutlined, MinusOutlined, PlusOutlined} from '@ant-design/icons';
import {reqBookInfos, reqDeleteBookInfo} from '../../api/book';
import {dateTimeDateFormat} from "../../utils/tools";
import {Link} from 'react-router-dom';
import './less/infos.less';

const { Search } = Input;

// 图书资讯
export default class BookInfo extends Component{
  search = '';
  state = {
    totalCount: 0,
    selectedRowKeys: [],
    dataSource: [],
    loading: true,
    searchLoading: false,
  }
  initColumns = () => {
    this.columns = [
      {
        title: '作者',
        dataIndex: 'author',
        key: 'author',
      },
      {
        title: '标题',
        key: 'title',
        render: (text, record) => <Link to={'/admin/books/infos/'+record._id}>{record.title}</Link>
      },
      {
        title: '头像',
        dataIndex: 'author_avatar',
        key: 'author_avatar',
        render: (author_avatar) => <Image src={author_avatar}/>
      },
      {
        title: '文章图像',
        dataIndex: 'note_image',
        key: 'note_image',
        render: (note_image) => <Image src={note_image} width={100}/>
      },
      {
        title: '源链接',
        dataIndex: 'detail_url',
        render: (detail_url) => <a href={detail_url}  rel="noopener noreferrer"
                                   target='_blank'>点击访问</a>
      },
      {
        title: '发布日期',
        dataIndex: 'pub_date',
        render: (pub_date) => dateTimeDateFormat(pub_date),
      }
    ];
  }

  getBookInfos = async (data) => {
    this.setState({loading: true}); // 非componentDidMount方法调用时显示loading
    try {
      const {data: res} = await reqBookInfos(data);
      this.setState({dataSource: res.items, totalCount: res.total_count, loading: false, searchLoading: false})
    } catch (e) {
      message.error(e.data.name || e.data.message);
      this.setState({loading: false})
    }
  }
  // 初始化table的col参数
  UNSAFE_componentWillMount() {
    this.initColumns();
  }

  componentDidMount() {
    this.getBookInfos();
  }
  // 搜索
  // 有值时，搜索，无值时就全查
  onSearch = (value, event) => {
    if (value !== '') {
      this.setState({searchLoading: true});
      this.search = value;
      this.getBookInfos({q: value});
    } else if (value === '' && this.search !== '') {
      this.search = '';
      this.getBookInfos();
    }
  }
  // 添加资讯
  addClick = () => {
    message.success('暂不支持添加资讯');
  }
  // 发起删除请求
  deleteInfo = async (data) => {
    try {
      await reqDeleteBookInfo(data);
      message.success('删除成功！');
      window.location.reload(); // 刷新当前页面,且不能有历史记录
    }catch (e) {
      message.error(e.data.name || e.data.message);
    }
  }
  // 点击模态框确认按钮 删除
  handleDelOk = (selectedRowKeys) => {
    this.deleteInfo({items: selectedRowKeys});
  }
  // 删除资讯
  deleteClick = () => {
    const {selectedRowKeys} = this.state;
    if (selectedRowKeys.length > 0) {
      Modal.confirm({
        title: '删除标签',
        icon: <ExclamationCircleOutlined/>,
        content: '请注意，你将永久删除该条资讯！',
        okText: '确认',
        cancelText: '取消',
        onOk: () => this.handleDelOk(selectedRowKeys),
      });
    }
  }
  // 全选资讯
  onSelectChange = (selectedRowKeys) => {
    this.setState({selectedRowKeys});
  }
  // table change事件
  onChange = (pagination, filters, sorter, extra) => {
    const {current, pageSize} = pagination;
    let data = {page: current, page_size: pageSize}
    if (this.search) {
      data = Object.assign(data, {q: this.search});
    }
    this.getBookInfos(data);
  }

  render () {
    const {selectedRowKeys, dataSource, totalCount, loading, searchLoading} = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    }

    const extra = (
      <Fragment>
        <Button type='primary' onClick={this.addClick} icon={<PlusOutlined/>} style={{marginRight: '10px'}}>
          添加
        </Button>
        <Button type='primary' danger onClick={this.deleteClick} icon={<MinusOutlined/>}>
          删除
        </Button>
      </Fragment>
    )

    const pagination = {
      defaultPageSize: 5,
      position: ['bottomCenter'],
      showQuickJumper: true,
      total: totalCount,
    }

    return (
      <Card title='图书资讯' extra={extra}>
        <div className='search-box'>
          <Search placeholder="搜索标题，作者"
                  onSearch={this.onSearch}
                  style={{ width: 200 }}
                  loading={searchLoading}/>
        </div>
        <Table dataSource={dataSource}
               columns={this.columns}
               rowKey='_id'
               scroll={{x: 800}}
               loading={loading}
               onChange={this.onChange}
               pagination={pagination}
               rowSelection={rowSelection}/>
      </Card>
    )
  }
}
